/*
 *  Copyright 2019-2023 oyun
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.oyun.modules.medicine.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oyun.annotation.Log;
import com.oyun.config.FileProperties;
import com.oyun.modules.medicine.domain.Hospital;
import com.oyun.modules.medicine.domain.HpPicture;
import com.oyun.modules.medicine.domain.vo.HospitalQueryCriteria;
import com.oyun.modules.medicine.mapper.HpPictureMapper;
import com.oyun.modules.medicine.service.HospitalService;
import com.oyun.utils.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author aoyun
 * @date 2024-04-25
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "医院管理")
@RequestMapping("/api/hospital")
public class HospitalController {


    private final HospitalService hospitalService;

    private final FileProperties properties;

    private final HpPictureMapper hpPictureMapper;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('hospital:list')")
    public void exportHospital(HttpServletResponse response, HospitalQueryCriteria criteria) throws IOException {
        hospitalService.download(hospitalService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询医院")
    @ApiOperation("查询医院")
    @PreAuthorize("@el.check('hospital:list')")
    public ResponseEntity<PageResult<Hospital>> queryHospital(HospitalQueryCriteria criteria, Page<Object> page) throws IOException {
        return new ResponseEntity<>(hospitalService.queryAll(criteria, page), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增医院")
    @ApiOperation("新增医院")
    @PreAuthorize("@el.check('hospital:add')")
    public ResponseEntity<Object> createHospital(@Validated @RequestBody Hospital resources) {
        hospitalService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改医院")
    @ApiOperation("修改医院")
    @PreAuthorize("@el.check('hospital:edit')")
    public ResponseEntity<Object> updateHospital(@Validated @RequestBody Hospital resources) {
        hospitalService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除医院")
    @ApiOperation("删除医院")
    @PreAuthorize("@el.check('hospital:del')")
    public ResponseEntity<Object> deleteHospital(@RequestBody List<Long> ids) {
        hospitalService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("上传医院图片")
    @PostMapping("/uploadProcessDefinition/{hpId}")
    public String uploadOrUpdate(MultipartFile file, HttpServletRequest request, @PathVariable("hpId") Long hpId) {
        return hospitalService.uploadOrUpdate(file, request, hpId);
    }

    @ApiOperation("查询名称")
    @GetMapping("/getNameAndId")
    public List<Hospital> getNameAndId() {
        return hospitalService.getNameAndId();
    }


//    @ApiOperation("根据汉语名称查询")
//    @GetMapping("/getByName/{zhName}")
//    public ResponseEntity<Object> getByUsername(@PathVariable("zhName") String zhName) {
//        return new ResponseEntity<>(hospitalService.getByName(zhName), HttpStatus.OK);
//    }

    @ApiOperation("根据名称查询")
    @GetMapping("/getByName")
    public ResponseEntity<Object> getByUsername(@RequestParam String name) {
        return new ResponseEntity<>(hospitalService.getByName(name), HttpStatus.OK);
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("images") MultipartFile[] images, @RequestParam("hpId") Long hpId) {
        FileProperties.ElPath path = properties.getPath();
        File filee = new File(properties.getPath().getPath() + "/upload");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        for (MultipartFile image : images) {
            String filename = image.getOriginalFilename();//获取文件名称带后缀名
            String uid = UUID.randomUUID().toString();//生成32为uuid值
            String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
            String newFile = uid + suffix;//拼接新的文件名称
            File file1 = new File(filee + "/" + newFile);
            try {
                image.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LambdaQueryWrapper<HpPicture> wrapper = new LambdaQueryWrapper<>();
            HpPicture hpPicture = new HpPicture();
            hpPicture.setHpId(hpId);
            hpPicture.setPathImage("/upload/" + newFile);
            hpPicture.setStatus(1);
            hpPictureMapper.insert(hpPicture);
        }
        return ResponseEntity.ok("图片上传成功。");
    }
}
